package com.account.service;


import com.account.dao.OrderDao;
import com.seata.api.AccountService;
import com.seata.api.OrderService;
import com.seata.api.tcc.AccountTccAction;
import com.seata.entity.Order;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;

@Slf4j
@DubboService
public class OrderServiceImpl implements OrderService {

    @Resource
    OrderDao orderDao;

    @DubboReference
    AccountService accountService;
    @DubboReference
    AccountTccAction accountTccAction; // 账户服务的tcc分布式事务控制

    @Override
    public Order create(String userId, String commodityCode, int orderCount) {

        // 计算订单的总金额。
        int orderMoney = calculate(commodityCode, orderCount);

        /**
         * 测试的时候，注意，这里如果打上断点之后。
         *  在查看Account表中的事务日志的时候，刷新3次之后，全局事务id立马
         *  被删除掉的现象，解决方式，就是yml配置全局事务xid的超时时长。
         */
//        accountService.debit(userId, orderMoney);
        accountTccAction.prepare(null, orderMoney);
//        int i = 1 / 0;

        Order order = new Order();
        order.setUserId(userId);
        order.setMoney(orderMoney);
        order.setCount(orderCount);
        order.setCommodityCode(commodityCode);
        // INSERT INTO orders ...
        log.info("新增订单，全局事务id：{}，分支事务：{}", RootContext.getXID(), RootContext.getBranchType());
        orderDao.insert(order);

        return order;
    }

    private int calculate(String commodityCode, int orderCount) {
        // 单件商品的金额
        int singleMoney = 100;
        return orderCount * singleMoney;
    }
}